<?php
namespace Core\Event\Application\Annotation;
use Core\Event\Annotation;
class Cache extends Annotation
{
    protected $_disabled = false;

    public function __construct($annotation) {
        $this->_disabled = ($this->request->getMethod() !== 'GET') ? true : false;
        parent::__construct($annotation);
    }

    protected function _getRequestId() {
        $method = $this->request->getMethod();
        $key = implode('|', [
            (int)$this->request->isAjax(),
            $this->request->getScheme(),
            $this->request->getHttpHost(),
            $this->request->getPort(),
            $this->dispatcher->getHandlerClass(),
            $this->request->getUri(),
            $method
        ]);
        return $key;
    }

    public function viewRender($event) {
        if(!$this->_disabled) {
            $mode = $this->_annotation->getNamedParameter('mode');
            if ($mode == 'view') {
                $option = [
                    'lifetime' => $this->_annotation->getNamedParameter('lifetime'),
                    'key' => $this->_annotation->getNamedParameter('key') ?: $this->_getRequestId()
                ];
                $this->view->cache($option);
            }
        }
        return true;
    }

    public function beforeHandleRequest($event) {
        if(!$this->_disabled) {
            $mode = $this->_annotation->getNamedParameter('mode');
            $key = $this->_annotation->getNamedParameter('key') ?: $this->_getRequestId();
            if ($mode == 'data' && ($returnedValue = $this->cache->start($key))){
                $this->response->setJsonContent($returnedValue)->send();
                exit;
            }
        }
        return true;
    }

    public function afterHandleRequest($event)
    {
        if(!$this->_disabled) {
            $mode = $this->_annotation->getNamedParameter('mode');
            $returnedValue = $this->dispatcher->getReturnedValue();
            if ($mode == 'data' && $returnedValue) {
                if ($this->cache->isStarted()) {
                    $lifetime = $this->_annotation->getNamedParameter('lifetime');
                    $key = $this->_annotation->getNamedParameter('key') ?: $this->_getRequestId();
                    $this->cache->save($key, $returnedValue, $lifetime);
                }
            }
        }
        return true;
    }
}